//
// Created by wujehy on 2020/7/11.
//

#include <iostream>
#include <mysql/mysql.h>
#include <MySQLCpp/Statement.h>
#include "MySQLCpp/DataBase.h"
using namespace GeeJoan::MySQL;
int main()
{
//     指定端口的构造方式
//    DataBase dataBase( "127.0.0.1", 33061, "test", "root", "123456" );
//  默认端口3306的构造方式
    DataBase dataBase( "127.0.0.1", "test", "root", "123456" );
//    选择数据库
//    dataBase.changeDB("test2");

// Test1 创建表
    try
    {
        std::string sql = "CREATE TABLE `test`.`Table`  (\n"
                          "  `id` int NOT NULL,\n"
                          "  `name` varchar(255) NULL,\n"
                          "  PRIMARY KEY (`id`)\n"
                          ");";
        int nb = dataBase.exec( sql );

        std::cout << " change = " << nb << std::endl;

    } catch (Exception &e)
    {
        std::cout << " ErrorCode " << e.getErrorCode() << std::endl;
        std::cout << " ExtendedErrorCode " << e.getExtendedErrorCode() << std::endl;std::cout << " e.what() " << e.what() << std::endl;
    }

// 插入数据 ， 使用stmt 模式
    try
    {
        std::string sql = " insert `test`.`Table`(`id` , `name` ) VALUES (?,?); ";
        // 最后一个参数是 说明需要绑定的数量 这里是 2 个 ？ 所以是2
        Statement statement( &dataBase, sql ,2);
        int id = 2;
        std::string name = "testname2";
        // 从 0 开始绑定 数据

        statement.bind( 0, id );
        statement.bind( 1, name );
        int nb = statement.exec();
        std::cout << " insert = " << nb << std::endl;

    } catch (Exception &e)
    {
        std::cout << " ErrorCode " << e.getErrorCode() << std::endl;
        std::cout << " ExtendedErrorCode " << e.getExtendedErrorCode() << std::endl;
        std::cout << " e.what() " << e.what() << std::endl;
    }

    try
    {
        std::string sql = " select * from `test`.`Table` ;";
        Statement statement( &dataBase, sql );

        int temp_id ;
        char temp_name[20];
//         　需要查询的　成员
        statement.result_size(2); // 查询２个
        //　绑定　查询的　类型
        statement.result_bind(0,&temp_id,0,MYSQL_TYPE_LONG);
        statement.result_bind(1,&temp_name,20,MYSQL_TYPE_STRING);

        int nb = statement.query();
        //标题
        for (int i = 0; i < statement.getFields().size(); ++i)
        {
            std::cout <<statement.getFields().at(i)<<"\t\t";
        }
        std::cout << std::endl;
        // 获取一行
        while (statement.Next())
        {
            std::cout <<temp_id << "\t\t"<<temp_name<<std::endl;
        }
        statement.reset();
    } catch (Exception &e)
    {
        std::cout << " ErrorCode " << e.getErrorCode() << std::endl;
        std::cout << " ExtendedErrorCode " << e.getExtendedErrorCode() << std::endl;
        std::cout << " e.what() " << e.what() << std::endl;
    }

    return 0;

}